<template>
	<form style="height: 100vh;background-color: white;padding-top: 7vh;">
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub" style="margin-top: 7vh;">
				<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage"
					:data-url="imgList[index]">
					<image :src="imgList[index]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
					<text class='cuIcon-cameraadd'></text>
				</view>
			</view>
		</view>
		<view class="cu-form-group ">
			<textarea maxlength="-1" :disabled="modalName!==null" @input="textareaAInput" placeholder="请输入详情"
				v-model="detail"></textarea>
		</view>
		<view class="cu-form-group">
			<view class="title">标题</view>
			<input placeholder="请输入标题" name="input" v-model="title" />
		</view>
		<view class="cu-form-group">
			<view class="title">地点</view>
			<input placeholder="请输入地点" name="input" v-model="place" />
		</view>
		<view class="cu-form-group">
			<view class="title">请选择活动类型</view>
			<picker @change="PickerChange1" :value="index1" :range="picker1">
				<view class="picker">
					{{index1>-1?picker1[index1]:'请选择活动类型'}}
				</view>
			</picker>
		</view>
		<view v-if="index1<=3&&index1>=0">
			<view class="rank">
				<text style="margin-right: 2vw;">技术:</text><van-rate v-model="value4"  void-icon="star" void-color="#bdbdbd"  />
			</view>
			<view class="rank">
				<text style="margin-right: 2vw;">速度:</text><van-rate v-model="value5"  void-icon="star" void-color="#bdbdbd" />
			</view>
			<view class="rank">
				<text style="margin-right: 2vw;">体力:</text><van-rate v-model="value6"  void-icon="star" void-color="#bdbdbd" />
			</view>
		</view>
		<view class="cu-form-group">
			<view class="title">开始时间</view>
			<picker mode="time" :value="time1" start="00:00" end="23:59" @change="TimeChange1">
				<view class="picker">
					{{time1}}
				</view>
			</picker>
		</view>
		<view class="cu-form-group">
			<view class="title">结束时间选择</view>
			<picker mode="time" :value="time2" start="00:00" end="23:59" @change="TimeChange2">
				<view class="picker">
					{{time2}}
				</view>
			</picker>
		</view>
		<view class="cu-form-group">
			<view class="title">开始日期</view>
			<picker mode="date" :value="date1" start="2015-01-01" end="2030-12-31" @change="DateChange1">
				<view class="picker">
					{{date1}}
				</view>
			</picker>
		</view>
		<view class="cu-form-group">
			<view class="title">结束日期</view>
			<picker mode="date" :value="date2" start="2015-01-01" end="2030-12-31" @change="DateChange2">
				<view class="picker">
					{{date2}}
				</view>
			</picker>
		</view>
		<view class="cu-form-group">
			<view class="title">状态</view>
			<picker @change="PickerChange" :value="index3" :range="picker3">
				<view class="picker">
					{{index3>-1?picker3[index3]:'请选择状态'}}
				</view>
			</picker>
		</view>
		<view class="btn">
			<button class="cu-btn round lg bg-red" @click="del(mesid)">删除</button>
			<button class="cu-btn round lg bg-blue" @click="sub">确定</button>
		</view>
	</form>
</template>

<script>
	import {
		uploadimg,
		pushpost,
		alterMypost,
		deleatpost,
		showpost,
		getTags
	} from '@/store/api.js'
	export default {
		data() {
			return {
				value4:0,
				value5:0,
				value6:0,
				mesid: '',
				userid: '',
				place: '',
				detail: '',
				title: '',
				index: -1,
				imgList: [],
				modalName: null,
				index1: -1,
				index2: -1,
				index3: -1,
				picker3: ['待匹配', '匹配完成', '挂起'],
				tag_id: [
				],
				picker1: [],
				// picker1: [],
				// picker2: ['松山湖', '莞城', '校外'],
				time1: '00:00',
				time2: '00:00',
				date1: new Date().toISOString().slice(0, 10),
				date2: new Date().toISOString().slice(0, 10),
			};
		},
		onLoad(value) {
			//获取帖子内容
			showpost(value.id).then(res => {
				console.log(res.data)
				this.mesid = res.data.id
				this.userid = res.data.posterId
				this.title = res.data.title

				this.date1 = res.data.beginTime.substring(0, 10)
				this.date2 = res.data.endTime.substring(0, 10)

				this.time1 = res.data.beginTime.substring(11, 16)
				this.time2 = res.data.endTime.substring(11, 16)
				//this.time = this.formatDate(res.data.beginTime) + '---' + this.formatDate(res.data.endTime)
				this.place = res.data.meetAddress

				this.index1 = res.data.tags[0].id - 1

				this.detail = this.processString(res.data.content).text
				this.imgList = this.processString(res.data.content).images
				
				this.value4=this.processString(res.data.content).rank.value4
				this.value5=this.processString(res.data.content).rank.value5
				this.value6=this.processString(res.data.content).rank.value6
			})
		},
		mounted() {
			getTags().then(res=>{
				console.log(res)
				this.tag_id=res.data.data
				res.data.data.forEach(item=>{
					this.picker1.push(item.name)
				})
			}).catch(err=>{
				console.log(err)
			})
		},
		methods: {
			onChange4(e){
				this.value4=e.detail
				// console.log(e.detail)
			},
			onChange5(e){
				this.value5=e.detail
				// console.log(e.detail)
			},
			onChange6(e){
				this.value6=e.detail
			},
			del(id) {
				uni.showModal({
					title: '提示',
					content: '确认删除该帖子吗？',
					success: function(res) {
						if (res.confirm) {
							console.log(id)
							const value = uni.getStorageSync('a_tk');
							uni.request({
								url: `/post/getme/${id}`,
								method: 'DELETE',
								header: {
									access_token: value
								},
								success: (res) => {
									console.log(res)
									uni.showToast({
										title: '删除成功',
										//将值设置为 success 或者直接不用写icon这个参数
										icon: 'success',
										//显示持续时间为 2秒
										duration: 1000
									})
									setTimeout(()=>{
										uni.navigateBack({
										    delta: 2, // Navigate back two steps
										    success: function () {
										        const pages = getCurrentPages(); // Get the current page stack
										        const prevPage = pages[pages.length - 2]; // Get the second-to-last page instance object
										        if (prevPage) {
										            prevPage.onLoad(); // Call the onLoad method of the second-to-last page
										        }
										    }
										},1000);

									})
								},
								fail: (err) => {
									console.log(err)
									uni.showToast({
										title: '删除失败',
										//将值设置为 success 或者直接不用写icon这个参数
										icon: 'fail',
										//显示持续时间为 2秒
										duration: 1000
									})
								}
							})
						} else {
							// 执行取消后的操作
						}
					}
				})
			},
			PickerChange(e) {
				this.index3 = e.detail.value
				const value = uni.getStorageSync('a_tk');
				let data = {
					postId: this.mesid,
					status: this.index3
				}
				uni.request({
					url: '/post/modify',
					data: data,
					method: 'POST',
					header: {
						access_token: value
					},
					success: (res) => {
						console.log(res)
						uni.showToast({
							title: '状态修改成功',
							//将值设置为 success 或者直接不用写icon这个参数
							icon: 'success',
							//显示持续时间为 2秒
							duration: 2000
						})
					},
					fail: (err) => {
						console.log(err)
						uni.showToast({
							title: '状态修改失败',
							//将值设置为 success 或者直接不用写icon这个参数
							icon: 'fail',
							//显示持续时间为 2秒
							duration: 2000
						})
					}
				})
			},
			formatDate(dateString) {
				const date = new Date(dateString);
				const hours = ('0' + date.getHours()).slice(-2);
				const minutes = ('0' + date.getMinutes()).slice(-2);
				const day = ('0' + date.getDate()).slice(-2);
				const month = ('0' + (date.getMonth() + 1)).slice(-2);
				const year = date.getFullYear();

				return `${hours}:${minutes} ${day}-${month}-${year}`;
			},
			processString(inputString) {
				const parts = inputString.split('**/img/**');

				// 获取文本部分和图片 URL 部分
				const textPart = parts[0];
				const imageUrls = parts[1] ? parts[1].split(',') : [];

				// 将图片 URL 部分存储为数组
				const imagesArray = imageUrls.map(url => url.trim());
				//获取评分栏
				const part2 = textPart.trim().split('**/rank/**')

				let newtext = part2[0]
				let rankpart = part2[1] ? JSON.parse(part2[1]) : ''
				console.log(rankpart)
				// 返回处理后的结果，图片部分作为数组返回
				return {
					rank: rankpart, //评分部分
					text: newtext.trim(), // 去除文本部分两端的空格
					images: imagesArray // 图片 URL 部分作为数组返回
				};

			},
			PickerChange1(e) {
				this.index1 = e.detail.value;
			},
			PickerChange2(e) {
				this.index2 = e.detail.value;
			},
			TimeChange1(e) {
				this.time1 = e.detail.value;
			},
			TimeChange2(e) {
				this.time2 = e.detail.value;
			},
			DateChange1(e) {
				this.date1 = e.detail.value;
			},
			DateChange2(e) {
				this.date2 = e.detail.value;
			},
			textareaAInput(e) {
				this.textareaAValue = e.detail.value;
			},
			textareaBInput(e) {
				this.textareaBValue = e.detail.value;
			},
			ChooseImage() {
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						uni.showLoading({
							title: '上传中...'
						});
						console.log(res.tempFilePaths)
						res.tempFilePaths.forEach(item => {
							console.log(item)
							uploadimg(item).then(res => {
								console.log(res)
								this.imgList.push(JSON.parse(res).data)
							})
						})
						uni.hideLoading()
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除吗？',
					cancelText: '再看看',
					confirmText: '再见',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},


			//修改
			sub() {
				uni.showLoading({
					title: '发布中...'
				});
				let tags = []
				let content = ''
				let ranks={
					value4:this.value4,
					value5:this.value5,
					value6:this.value6
				}
				if (this.imgList.length === 0&&this.index1>3) {
					content = this.detail
				} else if(this.imgList.length != 0&&this.index1>3){
					content = this.detail + '**/img/**' + this.imgList
				}else{
					content = this.detail+'**/rank/**'+JSON.stringify(ranks) + '**/img/**' + this.imgList
				}
				tags.push(this.tag_id[this.index1])
				let data = {
					id: this.mesid,
					title: this.title,
					meetAddress: this.place,
					beginTime: this.date1 + 'T' + this.time1 + ':00.000+00:00',
					endTime: this.date2 + 'T' + this.time2 + ':00.000+00:00',
					latitude: '',
					longtitude: '',
					tags: tags,
					content: content
				}
				console.log(data)
				alterMypost(data).then(res => {
					console.log(res)
					uni.hideLoading()
					uni.showToast({
						title: '发布成功！',
						//将值设置为 success 或者直接不用写icon这个参数
						icon: 'success',
						//显示持续时间为 2秒
						duration: 2000
					})
				}).catch(err => {
					console.log(err)
					uni.hideLoading()
					uni.showToast({
						title: '发布失败！',
						//将值设置为 success 或者直接不用写icon这个参数
						icon: 'fail',
						//显示持续时间为 2秒
						duration: 2000
					})
				})
			}
		},
	};
</script>


<style lang="scss" scoped>
	.rank{
		display: flex;
		align-items: center;
		padding-left: 4vw;
		font-size: 2ex;
		background-color: aliceblue;
	}
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.btn {
		display: flex;
		justify-content: space-evenly;
		width: 100%;
		text-align: center;
		margin-top: 10rpx;
	}

	.cu-btn {
		width: 40%;
	}
</style>